# -*- coding:utf-8 -*-
from config import config

try:
    from pymongo import MongoClient
except:
    print("请先安装mongodb库，执行如下命令：")
    print("pip install pymongo")

# mongodb

mongo_info = config.read_config("MONGODB")
MONGO_DB_IP = mongo_info["ip"]
MONGO_DB_PORT = int(mongo_info["port"])
MONGO_DB_USERNAME = mongo_info["username"]
MONGO_DB_PASSWORD = mongo_info["password"]
MONGO_DB_DATABASE = mongo_info["database"]

mg_conn, mg_db = None, None


def mongodb_exec(func):
    def child_wrapper(*args, **kwargs):
        global mg_conn, mg_db
        ret = None
        try:
            mg_conn = MongoClient(MONGO_DB_IP, MONGO_DB_PORT)
            mg_db = mg_conn[MONGO_DB_DATABASE]
            mg_db.authenticate(MONGO_DB_USERNAME, MONGO_DB_PASSWORD)
            ret = func(*args, **kwargs)
        finally:
            try:
                mg_conn.close()
            except:
                pass
        return ret

    return child_wrapper


@mongodb_exec
def mg_insert(set_name, dic):
    mg_set = mg_db[set_name]
    mg_set.insert(dic)


@mongodb_exec
def mg_update(set_name, dic, newdic):
    mg_set = mg_db[set_name]
    mg_set.update(dic, newdic)


@mongodb_exec
def mg_delete(set_name, dic):
    mg_set = mg_db[set_name]
    mg_set.remove(dic)


@mongodb_exec
def mg_query(set_name, dic, show=None):
    mg_set = mg_db[set_name]
    if show:
        data = mg_set.find(dic, show)
    else:
        data = mg_set.find(dic)
    return data


@mongodb_exec
def mg_aggregate(set_name, dic):
    mg_set = mg_db[set_name]
    data = mg_set.aggregate(dic)
    return data


if __name__ == '__main__':
    # print get_device_info()
    import json
    # with open("D:\\xProject_xGame2\\workspace\\art_diff_report\\static\\report\\report.json") as fp:
    #     report = json.load(fp)
    #     mg_insert("reports", {'date': '2017-09-22 14:40:32', 'commit_id1': 'ladkpiwe2342135345', 'commit_id2': 'ladoutoweotirrpq124212351', 'report_id': 'abcdef123456789', 'report': report})
    reports = mg_query("reports", {"commit_id1": "develop(a0941ee5c6)"}, {"report": 1, "date": 1, "_id": 0})   # [{"$group": {"_id": "$report_id", "commit_id1": "$commit_id1", "commit_id2": "$commit_id2", "date": "$date"}}])
    for report in reports:
        print json.dumps(report).decode("unicode_escape").encode("utf-8")
